package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.dto.UserInfo;
import com.ruoyi.bizsys.service.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.bizsys.utils.UserCacheService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.WebTokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: Jamnsin
 * @Date: 2021/3/10 6:12 下午
 */
@Slf4j
public class BaseService {

    @Autowired
    TokenService tokenService;

    @Autowired
    WebTokenService webTokenService;

    @Autowired
    IAppUserService appUserService;

    @Autowired
    ICustomerInfoService customerInfoService;

    @Autowired
    ISysDictDataService sysDictDataService;

    @Autowired
    ISysConfigService sysConfigService;

    @Autowired
    IRealNameAuthService realNameAuthService;

    @Autowired
    ICreditAccountService creditAccountService;

    @Autowired
    ICustBankCardService custBankCardService;

    @Autowired
    private UserCacheService userCacheService;

    public String getUserId() {
        String userId = null;
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null) {
            userId = loginUser.getUsername();
        }
        if (StringUtils.isBlank(userId)) {
            log.warn("用户不存在或登录态失效");
            throw new BusinessException(RspEnmu.ILLEGAL_USER_REQ_ERR);
        }
        return userId;
    }

    public String webGetUserId() {
        String userId = null;
        LoginUser loginUser = webTokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null) {
            userId = loginUser.getUsername();
        }
        if (StringUtils.isBlank(userId)) {
            log.warn("用户不存在或登录态失效");
            throw new BusinessException(RspEnmu.ILLEGAL_USER_REQ_ERR);
        }
        return userId;
    }


    public String getCustNo2() {
        UserInfo userInfo = userCacheService.getUserCacheInfo();
        return userInfo.getCustNo();
    }

    protected String getAppVersion() {
        String appVersion = ServletUtils.getRequest().getHeader("appVersion");
        log.info("获取appVersion = {}", appVersion);
        if (Func.isEmpty(appVersion)) {
            log.info("appVersion is null");
            throw new BusinessException(RspEnmu.APP_VERSION_DONOT_SUPPORT);
        }
        return appVersion;
    }


    protected int formatAppVersion(String appVersion) {
        return Integer.parseInt(appVersion.replaceAll("\\.", ""));
    }

    protected String getCustNo() {
        return customerInfoService.getCustNoByUserId(getUserId());
    }

    protected String getCustNo(String userId) {
        return getCustInfoByUserId(userId).getCustNo();
    }

    public CustomerInfo getCustomerInfo() {
        return getCustInfoByUserId(this.getUserId());
    }

    protected String getUserIdByCustNo(String custNo) {
        QueryWrapper<CustomerInfo> customerInfoQueryWrapper = new QueryWrapper<>();
        customerInfoQueryWrapper.eq("cust_no", custNo).eq("state", UserConstants.BUSINESS_NORMAL).select("user_id").last("limit 1");
        return customerInfoService.getOne(customerInfoQueryWrapper).getUserId();
    }

    protected AppUser getAppUserByCustNo(String custNo) {
        AppUser result = null;
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustNo(custNo);
        customerInfo.setState(BizConstants.BIZ_STATUS_1);
        List<CustomerInfo> customerInfoList = customerInfoService.selectCustomerInfoList(customerInfo);
        if (customerInfoList.size() == 1) {
            customerInfo = customerInfoList.get(0);
            AppUser appUser = new AppUser();
            appUser.setUserUuid(customerInfo.getUserId());
            appUser.setState("0");
            List<AppUser> appUserList = appUserService.selectAppUserList(appUser);
            if (appUserList.size() == 1) {
                result = appUserList.get(0);
            }
        }
        return result;
    }

    protected CustomerInfo getCustInfoByUserId(String userId) {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setUserId(userId);
        customerInfo.setState(BizConstants.BIZ_STATUS_1);
        List<CustomerInfo> customerInfoList = customerInfoService.selectCustomerInfoList(customerInfo);
        if (CollectionUtils.isEmpty(customerInfoList)) {
            throw new BusinessException(RspEnmu.CUSTOMER_IS_NOT_EXISTS);
        }

        return customerInfoList.get(0);
    }

    public CustomerInfo getCustInfo(String custNo) {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustNo(custNo);
        customerInfo.setState(BizConstants.BIZ_STATUS_1);
        List<CustomerInfo> customerInfoList = customerInfoService.selectCustomerInfoList(customerInfo);
        if (CollectionUtils.isEmpty(customerInfoList)) {
            throw new BusinessException(RspEnmu.CUSTOMER_IS_NOT_EXISTS);
        }

        return customerInfoList.get(0);
    }

    protected AppUser getAppUser() {
        AppUser appUser = new AppUser();
        appUser.setUserUuid(this.getUserId());
        List<AppUser> appUsers = appUserService.selectAppUserList(appUser);
        if (CollectionUtils.isEmpty(appUsers)) {
            throw new BusinessException(RspEnmu.USER_NOT_EXIST);
        }

        return appUsers.get(0);
    }

    /**
     * H5 web单独获取的方式
     *
     * @return
     */
    protected AppUser webGetAppUser() {
        AppUser appUser = new AppUser();
        appUser.setUserUuid(this.webGetUserId());
        List<AppUser> appUsers = appUserService.selectAppUserList(appUser);
        if (CollectionUtils.isEmpty(appUsers)) {
            throw new BusinessException(RspEnmu.USER_NOT_EXIST);
        }

        return appUsers.get(0);
    }

    /**
     * 用户是否登录
     *
     * @return
     */
    protected boolean getUserOnline() {
        LoginUser user = tokenService.getLoginUser(ServletUtils.getRequest());
        if (user != null) {
            return true;
        }
        return false;
    }

    protected AppUser getAppUser(String userId) {
        AppUser appUser = new AppUser();
        appUser.setUserUuid(userId);
        List<AppUser> appUsers = appUserService.selectAppUserList(appUser);
        if (CollectionUtils.isEmpty(appUsers)) {
            throw new BusinessException(RspEnmu.USER_NOT_EXIST);
        }

        return appUsers.get(0);
    }

    protected RealNameAuth getRealNameAuth() {
        RealNameAuth auth = new RealNameAuth();
        auth.setUserId(getUserId());
        auth.setState(BizConstants.BIZ_STATUS_1);
        List<RealNameAuth> realNameAuthList = realNameAuthService.selectRealNameAuthList(auth);
        RealNameAuth realNameAuth = realNameAuthList.get(0);
        return realNameAuth;
    }

    protected RealNameAuth getRealNameAuth(String userId) {
        RealNameAuth auth = new RealNameAuth();
        auth.setUserId(userId);
        auth.setState(BizConstants.BIZ_STATUS_1);
        List<RealNameAuth> realNameAuthList = realNameAuthService.selectRealNameAuthList(auth);
        RealNameAuth realNameAuth = realNameAuthList.get(0);
        return realNameAuth;
    }

    protected RealNameAuth getRealNameByCustNo(String custNo) {
        RealNameAuth auth = new RealNameAuth();
        auth.setCustNo(custNo);
        auth.setState(BizConstants.BIZ_STATUS_1);
        List<RealNameAuth> realNameAuthList = realNameAuthService.selectRealNameAuthList(auth);
        RealNameAuth realNameAuth = realNameAuthList.get(0);
        return realNameAuth;
    }

    protected CustBankCard getDefaultCardByCust(String cust) {
        CustBankCard custBankCard = new CustBankCard();
        custBankCard.setCustNo(cust);
        custBankCard.setIsDefault("Y");
        List<CustBankCard> custBankCards = custBankCardService.selectCustBankCardList(custBankCard);
        if (!CollectionUtils.isEmpty(custBankCards)) {
            throw new BusinessException(RspEnmu.CUSTOMER_IS_NOT_EXISTS);
        }
        return custBankCards.get(0);
    }

    public CreditAccount getCreditAccount() {
        List<CreditAccount> creditAccountList = getCreditAccounts(getCustNo());
        return creditAccountList.get(0);
    }

    public CreditAccount getCreditAccount(String custNo) {
        List<CreditAccount> creditAccountList = getCreditAccounts(custNo);
        return creditAccountList.get(0);
    }

    private List<CreditAccount> getCreditAccounts(String custNo) {
        CreditAccount ca = new CreditAccount();
        ca.setCustNo(custNo);
        ca.setState(BizConstants.BIZ_STATUS_1);
        List<CreditAccount> creditAccountList = creditAccountService.selectCreditAccountList(ca);
        if (CollectionUtils.isEmpty(creditAccountList)) {
            throw new BusinessException(RspEnmu.CUSTOMER_IS_NOT_EXISTS);
        }
        return creditAccountList;
    }

    protected int updateAppUserById(AppUser appUser) {
        return appUserService.updateAppUser(appUser);
    }

    protected String getDictLabel(String dictType, String dictValue) {
        return sysDictDataService.selectDictLabel(dictType, dictValue);
    }

    protected boolean appGpReviewSwitch() {
        return Integer.valueOf(getDictLabel("biz_switch", "app_gp_in_review")) == 1;
    }

}
